<!--  -->
<template>
  <ContainerLayout class="user-self">
    <div class="user-self-cell form-container">
      <div class="header-controls">
        <div class="control-buttons">
          <el-button :icon="ArrowLeftBold" link type="primary" @click="handleClickBtnPrevYear"></el-button>
          <div class="month-selector">
            {{ year }}
            <el-date-picker class="datepicker" v-model="currentMonth" type="year" placeholder="选择月份" style="position: absolute; left: 50%; opacity: 0; transform: translateX(-50%); width: 100%" />
          </div>
          <el-button :icon="ArrowRightBold" link type="primary" @click="handleClickBtnNextYear"></el-button>
        </div>
      </div>
      <el-button type="primary" @click="handleClickBtnApplyLeave()">申请休假</el-button>
    </div>
    <el-divider />
    <div class="user-self-cell category-cells">
      <el-scrollbar style="width: 100%; text-align: left">
        <el-space v-if="loadFlag">
          <HolidayCard v-for="item in holidayCategoryList" :item="item" :user-name="currentUser.username" :year-num="currentYear.getFullYear()" :rows-holiday="rowsHoliday" :rows-leave="rowsHoliday" @click="handleClickHolidayCard" />
        </el-space>
      </el-scrollbar>
    </div>
    <el-divider />
    <div class="user-self-cell table-container">
      <div class="tool-bar">
        <div class="tags-cells"></div>
        <div style="display: flex; justify-content: center; align-items: center">
          <div class="" style="display: flex">
            <el-button :icon="ArrowLeftBold" link type="primary" @click="handleClickBtnPrevMonth"></el-button>
            <div class="month-selector">
              {{ month }}
              <el-date-picker class="datepicker" v-model="currentMonth" type="month" placeholder="选择月份" style="position: absolute; left: 50%; opacity: 0; transform: translateX(-50%); width: 100%" />
            </div>
            <el-button :icon="ArrowRightBold" link type="primary" @click="handleClickBtnNextMonth"></el-button>
          </div>
        </div>
        <div class="tags-cells">
          <el-space wrap direction="horizontal">
            <el-tag v-for="tag in holidayTags" :key="tag.dictValue" size="large" :disable-transitions="true" closable type="info" @close="handleCloseTag(tag)">
              {{ tag.dictLabel }}
            </el-tag>
          </el-space>
        </div>

        <el-space direction="horizontal" wrap alignment="start" :size="20">
          <el-select v-model="holidayCategoryValue" collapse-tags clearable placeholder="类型" style="width: 100px">
            <el-option v-for="item in holidayCategoryList" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
          </el-select>
          <el-select v-model="leaveCategoryValue" collapse-tags clearable placeholder="状态" style="width: 100px">
            <el-option v-for="item in leaveCategoryList" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
          </el-select>
        </el-space>
      </div>
      <div class="item-cells" ref="itemCells">
        <el-scrollbar :height="scrollbarHeight" always>
          <el-space direction="vertical" :fill="true" wrap class="detail-cells">
            <el-card v-for="item in leaveList" shadow="never">
              <div class="cell">
                <div class="date">
                  <el-text type="primary" size="large">{{ item.leaveDate }}</el-text>
                </div>
                <div class="detail">
                  <div class="vacation-info">
                    <div class="vacation-type">
                      <el-text><TextTeg :id="item.leaveCategory * 1" /></el-text>
                    </div>
                    <div class="vacation-days">
                      <el-text>{{ item.startTime }} 到 {{ item.endTime }}</el-text>
                    </div>
                  </div>
                  <el-space wrap>
                    <el-tag type="primary" v-if="item.approvalUserNick">当前审批人：{{ item.approvalUserNick }}</el-tag>
                    <el-button v-if="item.leaveStatus * 1 == 1 || item.leaveStatus * 1 == 2 || item.leaveStatus * 1 == 9" type="danger" :icon="Delete" size="small" plain @click="handleClickBtnDleLeave(item)">删除</el-button>
                    <el-button v-if="false" -v-else-if="item.leaveStatus * 1 == 2" type="warning" :icon="RefreshLeft" size="small" plain @click="handleClickBtnRevokeLeave(item)">撤销</el-button>
                  </el-space>
                </div>
                <div class="state">
                  <el-text v-if="item.leaveStatus" :type="getStatusType(item.leaveStatus * 1)">{{ getStatus(item.leaveStatus) }}</el-text>
                </div>
              </div>
            </el-card>
          </el-space>
        </el-scrollbar>
      </div>
    </div>
  </ContainerLayout>
  <DialogLeave ref="dialogLeaveRef" @submit-successed="handleDialogSubmitSuccessed" />
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import ContainerLayout from '../layout/ContainerLayout.vue'
import { useHolidayCategoryStore, useUsersStore, useLeaveCategoryStore } from '../stores'
import { ArrowLeftBold, ArrowRightBold, Delete, RefreshLeft } from '@element-plus/icons-vue'
import { formatDate } from '../utils'
import api from '../api'
import TextTeg from '../components/TableParts/TextTeg.vue'
import DialogLeave from '../components/dialog/DialogLeave.vue'
import HolidayCard from '../components/UserSelf/HolidayCard.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const holidayCategoryList = useHolidayCategoryStore().getAllState()
const holidayCategoryValue = ref()
const leaveCategoryList = ref(useLeaveCategoryStore().getAllState())
const leaveCategoryValue = ref()
const dialogLeaveRef = ref()
const scrollbarHeight = ref(400)
const itemCells = ref(ref<HTMLElement | null>(null))
// const vacationState = ref(-1)
const currentMonth = ref(new Date())
const currentYear = ref(new Date())
const currentUser = useUsersStore().getAllState()
const leaveList = ref<any[]>([])
const rowsHoliday = ref<any[]>([])
const loadFlag = ref<boolean>(false)

const year = computed(() => {
  if (currentYear.value) {
    return formatDate(currentYear.value, 'yyyy年')
  } else {
    return ''
  }
})
const month = computed(() => {
  if (currentMonth.value) {
    return formatDate(currentMonth.value, 'yyyy年MM月')
  } else {
    return ''
  }
})
const holidayTags = computed(() => {
  if (holidayCategoryValue.value) {
    // console.log(holidayCategoryValue.value)
    const items: any = []
    // holidayCategoryValue.value.forEach((item: any) => {
    //   items.push(holidayCategoryList.find((e) => item === e.dictValue))
    // })
    return items
  } else {
    return []
  }
})

watch([() => holidayCategoryValue.value, () => leaveCategoryValue.value, () => currentMonth.value], async () => {
  await getLeaveList()
})
/**
 * 处理关闭标签的函数
 *
 * @param item 标签项对象
 * @returns 无返回值
 */
const handleCloseTag = async (item: any) => {
  holidayCategoryValue.value = holidayCategoryValue.value.filter((e: any) => e !== item.dictValue)
}

/**
 * 点击上月按钮时调用的函数
 *
 * @returns 无返回值
 */
const handleClickBtnPrevMonth = () => {
  currentMonth.value = new Date(currentMonth.value!.getFullYear(), currentMonth.value!.getMonth() - 1, 1)
}

/**
 * 点击“下月”按钮的处理函数
 *
 * @returns 无返回值
 */
const handleClickBtnNextMonth = () => {
  currentMonth.value = new Date(currentMonth.value!.getFullYear(), currentMonth.value!.getMonth() + 1, 1)
}

/**
 * 点击上一年按钮的处理函数
 *
 * 将当前年份减1，并重置月份和日期为1月1日
 */
const handleClickBtnPrevYear = () => {
  currentYear.value = new Date(currentYear.value!.getFullYear() - 1, 0, 1)
}
/**
 * 处理点击“下一年”按钮的事件
 *
 * @returns 无返回值
 */
const handleClickBtnNextYear = () => {
  currentYear.value = new Date(currentYear.value!.getFullYear() + 1, 0, 1)
}
const handleDialogSubmitSuccessed = async () => {
  await getLeaveList()
  await getUserLeave()
}
const getStatus = (status: any) => {
  return leaveCategoryList.value.find((e: any) => e.dictValue === status.toString())?.dictLabel || ''
}
const getStatusType = (status: number) => {
  // leaveCategoryList.value.find((e: any) => e.dictValue === status.toString())?.dictLabel || ''
  let result = 'info' // 6: 未提交, 9: 已撤销
  // 0: 已驳回, 1: 待审核, 2: 审批中, 3: 审批通过, 6: 未提交, 8: 通过后撤销, 9: 已撤销
  switch (status) {
    case 1:
    case 2:
      result = 'primary'
      break
    case 0:
      result = 'danger'
      break
    case 3:
      result = 'success'
      break
    case 8:
      result = 'warning'
      break
  }
  return result
}

/**
 * 获取请假列表的异步函数
 *
 * @returns 无返回值
 */
const getLeaveList = async () => {
  const start = new Date(currentMonth.value!.getFullYear(), currentMonth.value!.getMonth(), 1)
  // 原代码（获取当月最后一天）
  // const end = new Date(currentMonth.value!.getFullYear(), currentMonth.value!.getMonth() + 1, 0);

  // 调整为下月第一天
  const end = new Date(
    currentMonth.value!.getFullYear(),
    currentMonth.value!.getMonth() + 1, // 关键变化：去掉 ", 0"
    1 // 明确指定第一天
  )
  const params = {
    pageSize: 99999,
    userName: currentUser.username,
    startLeaveDate: formatDate(start, 'yyyy-MM-dd'),
    endLeaveDate: formatDate(end, 'yyyy-MM-dd'),
  }
  // if (vacationState.value > -1) {
  //   // Object.assign(params, { leaveStatus: vacationState.value })
  //   Object.assign(params, { leaveStatus: vacationState.value })
  // }

  if (holidayCategoryValue.value) {
    Object.assign(params, { leaveCategory: holidayCategoryValue.value })
  }
  if (leaveCategoryValue.value) {
    Object.assign(params, { leaveStatus: leaveCategoryValue.value })
  }
  leaveList.value = await api.Leave.getList(params)
}

const handleClickBtnApplyLeave = (leaveCategory: any = null) => {
  // console.log('leaveCategory', leaveCategory)
  // getLeaveList()
  if (dialogLeaveRef.value) {
    dialogLeaveRef.value.openDialog(new Date(), leaveCategory)
  }
}

const handleClickHolidayCard = async (item: any) => {
  handleClickBtnApplyLeave(item)
}

const getUserLeave = async () => {
  loadFlag.value = false
  const params = {
    userName: currentUser.username,
    yearNum: currentMonth.value!.getFullYear(),
  }
  const rows = await api.Holiday.getSearch(params)
  rowsHoliday.value = rows
  loadFlag.value = true
}

/**
 * 处理点击删除按钮的事件
 *
 * @param item 要删除的数据项
 */
const handleClickBtnDleLeave = async (item: any) => {
  ElMessageBox.confirm('确定删除?', '提示')
    .then(async () => {
      const { code } = await api.Leave.deleteById(item.id)
      // console.log('code', code)
      if (code !== 200) {
      } else {
        ElMessage({
          message: `删除成功！`,
          grouping: true,
          type: 'success',
        })
      }
      handleDialogSubmitSuccessed()
    })
    .catch(() => {})
}

/**
 * 处理点击撤销请假按钮的逻辑
 *
 * @param item 请假条数据
 */
const handleClickBtnRevokeLeave = async (item: any) => {
  ElMessageBox.confirm('确定撤销请假吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const { code } = await api.Leave.putRevokeById(item.id)
      if (code !== 200) {
      } else {
        ElMessage({
          message: `撤销成功！`,
          grouping: true,
          type: 'success',
        })
      }
      handleDialogSubmitSuccessed()
    })
    .catch(() => {})
}
onMounted(async () => {
  await getLeaveList()
  await getUserLeave()
  if (itemCells.value) {
    scrollbarHeight.value = itemCells.value.offsetHeight
  }
})
</script>
<style lang="scss" scoped>
.user-self {
  display: flex;
  flex-direction: column;
  .form-container {
    display: flex;
    .header-controls {
      flex: 1;
      display: flex;
      justify-content: center;
      .control-buttons {
        display: flex;
        align-items: center;
      }
    }
  }
  .category-cells {
    display: flex;
    flex-wrap: wrap;
  }
  .detail-cells {
    width: 100%;
  }
  .month-selector {
    position: relative;
    padding: 0 10px;
  }
  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    .tool-bar {
      margin-bottom: 10px;
      display: flex;
      .tags-cells {
        flex: 1;
        display: flex;
        justify-content: flex-start;
        padding: 0 20px;
      }
    }
    .item-cells {
      flex: 1;
      .cell {
        display: flex;
        margin: -10px;

        .date,
        .state {
          width: auto;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        .detail {
          flex: 1;
          text-align: left;
          padding: 0 10px;
          margin: 0 10px;
          border-left: 1px solid var(--el-border-color);

          border-right: 1px solid var(--el-border-color);

          display: flex;
          justify-content: center;
          align-items: center;

          .vacation-info {
            flex: 1;
            .vacation-type,
            .vacation-days {
              line-height: 1.2;
            }
          }
        }
        .state {
          width: 120px;
        }
      }
    }
  }
}
</style>
